import { lazyReportBatch } from "../report";
import generateUniqueId from "../utils";

export default function pageChange() {
  // hash history change

  let oldUrl = "";
  window.addEventListener(
    "hashchange",
    (event) => {
      const newUrl = event.newURL;
      const reportData = {
        from: oldUrl,
        to: newUrl,
        type: "behavior",
        subType: "hashChange",
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };

      lazyReportBatch(reportData);
      oldUrl = newUrl;
    },
    true
  );

  let from = "";
  window.addEventListener(
    "popstate",
    (event) => {
      const to = window.location.href;
      const reportData = {
        from: from,
        to: newUrl,
        type: "behavior",
        subType: "popstate",
        startTime: performance.now(),
        uuid: generateUniqueId(),
      };

      lazyReportBatch(reportData);
      from = to;
    },
    true
  );
}
